package binaryTree;

import org.junit.Test;

import java.util.List;

/*
 *@description 二叉搜索树中第 K 小的元素
 *@author hkfan
 *@version 1.0
 *@create 2025/6/10 14:46
 */
public class LeetCode_230 {
    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode() {}
        TreeNode(int val) { this.val = val; }
        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    int res,i;


    public int kthSmallest(TreeNode root, int k) {
//        List<Integer> list = new ArrayList<>();
//        solution_1(root,list);
//        return list.get(k-1);
        solution_2(root,k);
        return res;
    }

    @Test
    public void test(){
        TreeNode root = new TreeNode(5);

        TreeNode node1 = new TreeNode(3);
        TreeNode node2 = new TreeNode(6);
        TreeNode node3 = new TreeNode(2);
        TreeNode node4 = new TreeNode(4);
        TreeNode node5 = new TreeNode(1);
        root.left=node1;
        root.right=node2;
        node1.left=node3;
        node1.right=node4;
        node3.left=node5;
        System.out.println(kthSmallest(root,3));
    }

    private void solution_2(TreeNode root, int k) {
        if (root==null){
            return;
        }
        if (root.left!=null){
            solution_2(root.left,k);
        }
        i++;
        if (i==k){
            res=root.val;
        }
        if (root.right!=null){
            solution_2(root.right,k);
        }
    }

    private void solution_1(TreeNode root, List<Integer> list) {
        if (root==null){
            return;
        }
        if (root.left!=null){
            solution_1(root.left,list);
        }
        list.add(root.val);
        if (root.right!=null){
            solution_1(root.right,list);
        }
    }
}
